package com.maciek.integracja_aplikacji.dao.impl;

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.maciek.integracja_aplikacji.dao.PersonDao;
import com.maciek.integracja_aplikacji.model.Person;

public class PersonDaoImpl extends HibernateDaoSupport implements PersonDao {
	
	public void save(Person person) {
		getHibernateTemplate().save(person);
	}
	
	public void update(Person person) {
		getHibernateTemplate().update(person);
	}
	
	public void delete(Person person) {
		getHibernateTemplate().delete(person);
	}
	
	public Person findBy(String firstName, String lastName, String pesel) {
		
		String expression = "from Person where ";
		boolean flag = false;
		
		if(!"".equals(firstName) && firstName != null) {
			expression += flag ? " and " : "";
			expression += "PERSON_FIRST_NAME='" + firstName + "'";
			flag = true;
		}
		if(!"".equals(lastName) && lastName != null) {
			expression += flag ? " and " : "";
			expression += "PERSON_LAST_NAME='" + lastName + "'";
			flag = true;
		}
		if(!"".equals(pesel) && pesel != null) {
			expression += flag ? " and " : "";
			expression += "PERSON_PESEL='" + pesel + "'";
			flag = true;
		}
		
		List list = getHibernateTemplate().find(expression);
		
		try{
			return (Person)list.get(0);
		} catch(IndexOutOfBoundsException e) {
			return null;
		}
	}

}
